package com.linchong.concurrency.chapter10.v1;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * @Author:linchong
 * @CreateTime:2020-07-28 11:47
 * @Description:
 */
public class LockTest {

	public static void main(String[] args) {
		final BooleanLock booleanLock = new BooleanLock();
		Stream.of("T1","T2","T3","T4")
				.forEach(name->
					new Thread(()->{
						try {
							booleanLock.lock(10L);
							Optional.of(Thread.currentThread().getName() + " have the lock monitor")
								.ifPresent(System.out::println);
							work();
						} catch (InterruptedException e) {
							e.printStackTrace();
						} catch (Lock.TimeOutException e) {
							Optional.of(Thread.currentThread().getName()
								+ " times out")
								.ifPresent(System.out::println);
						} finally {
							booleanLock.unlock();
						}
					},name).start()
				);
		//自定义锁的实现，其他人可以调用，如此可导致某个加锁的线程在还未完成的情况下，其他线程加入，其他的线程有机会去释放当前锁
//		//正常的应该是谁加的锁，谁去释放,解决方案，根据调用线程去判断，只有当前的线程可以释放当前线程的锁
//		Thread.sleep(100);
//		booleanLock.unlock();
	}

	public static void work() throws InterruptedException {
		Optional.of(Thread.currentThread().getName() + " is working...")
				.ifPresent(System.out::println);
		Thread.sleep(30_000);

	}
}
